<template>
  <div class="wrapper">
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>钱包提现</p>
    </header>
    <div class="content">
      <div class="section">
        <div class="title">提现金额</div>
        <input type="number" v-model.number="amount" @input="calculateDeduction" placeholder="输入金额" />
        <div class="hint" :class="balanceOk ? 'ok' : 'err'">{{ balanceText }}</div>
      </div>
      <div v-if="amount > 0" class="section">
        <div class="title">扣减明细</div>
        <div class="deduction-detail">
          <div class="detail-item">
            <span>奖励金额扣减：</span>
            <span class="amount">¥{{ formatCurrency(rewardDeduct) }}</span>
          </div>
          <div class="detail-item">
            <span>手续费：</span>
            <span class="amount">¥{{ formatCurrency(feeAmount) }}</span>
          </div>
          <div class="detail-item total">
            <span>总扣减金额：</span>
            <span class="amount">¥{{ formatCurrency(totalDeduct) }}</span>
          </div>
          <div class="deduction-note">💡 提现时优先扣减奖励金额</div>
        </div>
      </div>
      <div class="section">
        <div class="title">到账账户</div>
        <select v-model="account">
          <option value="alipay">支付宝</option>
          <option value="wechat">微信</option>
          <option value="card">银行卡</option>
        </select>
      </div>
      <div class="section">
        <div class="title">手续费</div>
        <div class="fee">{{ feeText }}</div>
      </div>
      <div class="section">
        <button class="confirm" :disabled="!canSubmit" @click="confirmWithdraw">确认提现</button>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import Footer from '../components/Footer.vue'
import { ref, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { walletApi } from '../api'

const router = useRouter()
const amount = ref(100)
const account = ref('alipay')
const balanceOk = ref(true)
const balanceText = ref('余额充足')
const feeRate = ref(0)
const wallet = ref(null)
const rewardDeduct = ref(0)
const feeAmount = ref(0)
const totalDeduct = ref(0)

const fetchWalletAndRules = async () => {
  try {
    // 获取钱包信息
    wallet.value = await walletApi.getMyWallet()

    // 获取提现规则
    const rules = await walletApi.getActiveRules()
    const w = Array.isArray(rules) ? rules.find(r => r.ruleType === 'WITHDRAW') : null
    feeRate.value = Number(w?.ruleValue || 0)
    
    // 如果已有金额输入，重新计算扣减明细
    if (amount.value > 0) {
      await calculateDeduction()
    }
  } catch (e) {
    console.error('获取钱包或规则信息失败:', e)
  }
}
fetchWalletAndRules()
const formatCurrency = v => {
  const n = Number(v || 0)
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
const feeText = computed(() => `预计手续费约 ¥${formatCurrency(Number(amount.value || 0) * feeRate.value)}`)
const canSubmit = () => Number(amount.value) > 0 && balanceOk.value

const calculateDeduction = async () => {
  if (!amount.value || amount.value <= 0) {
    rewardDeduct.value = 0
    feeAmount.value = 0
    totalDeduct.value = 0
    balanceOk.value = true
    balanceText.value = '请输入提现金额'
    return
  }

  // 确保钱包信息已加载
  if (!wallet.value) {
    try {
      wallet.value = await walletApi.getMyWallet()
    } catch (e) {
      console.error('获取钱包信息失败:', e)
      return
    }
  }

  // 计算手续费
  feeAmount.value = Number(amount.value) * feeRate.value

  // 检查余额是否足够（包含手续费）
  const totalNeeded = amount.value + feeAmount.value
  const ok = await walletApi.checkBalanceSufficient(totalNeeded)
  balanceOk.value = !!ok
  balanceText.value = ok ? '余额充足' : '余额不足'

  if (ok && wallet.value) {
    // 优先扣减奖励金额的逻辑：奖励金额扣减 = min(奖励余额, 提现金额 + 手续费)
    const rewardBalance = Number(wallet.value.rewardAmount || 0)
    rewardDeduct.value = Math.min(rewardBalance, totalNeeded)

    // 总扣减金额 = 提现金额 + 手续费
    totalDeduct.value = totalNeeded
  } else {
    rewardDeduct.value = 0
    feeAmount.value = 0
    totalDeduct.value = 0
  }
}

watch(amount, calculateDeduction)

const confirmWithdraw = async () => {
  const rewardText = rewardDeduct.value > 0 ? ` (扣减奖励¥${formatCurrency(rewardDeduct.value)})` : ''
  const feeText = feeAmount.value > 0 ? ` (手续费¥${formatCurrency(feeAmount.value)})` : ''
  const ok = window.confirm(`确认提现 ¥${formatCurrency(amount.value)} 至 ${displayAccount()} 吗？\n${rewardText}${feeText}`)
  if (!ok) return
  const pw = window.prompt('请输入交易密码')
  if (!pw) return
  await simulateThirdParty()
  await walletApi.withdraw({ amount: amount.value, remark: `提现-${account.value}` })
  await router.push('/wallet')
}

const displayAccount = () => ({ alipay: '支付宝', wechat: '微信', card: '银行卡' }[account.value])
const simulateThirdParty = () => new Promise(resolve => setTimeout(resolve, 1000))
const goBack = () => router.push('/wallet')
</script>

<style scoped>
.wrapper { width: 100%; min-height: 100%; }
header { width: 100%; height: 12vw; background-color: #0097ff; color: #fff; font-size: 4.8vw; position: fixed; left: 0; top: 0; z-index: 1000; display: flex; justify-content: center; align-items: center; }
header i { position: absolute; left: 3vw; font-size: 6vw; color: #fff; cursor: pointer; }
.content { margin-top: 14vw; padding: 4vw; }
.section { margin-bottom: 6vw; }
.title { font-size: 4vw; color: #666; margin-bottom: 2vw; }
input, select { width: 100%; height: 10vw; border: 1px solid #ddd; border-radius: 2vw; padding: 0 3vw; font-size: 4vw; }
.hint { margin-top: 2vw; font-size: 3.6vw; }
.hint.ok { color: #38ca73; }
.hint.err { color: #ff6b35; }
.fee { font-size: 4vw; color: #333; }
.confirm { width: 100%; height: 10vw; border: none; border-radius: 2vw; background: #38ca73; color: #fff; font-size: 4vw; font-weight: 700; }
.deduction-detail { background: #f8f9fa; border-radius: 2vw; padding: 3vw; }
.detail-item { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2vw; font-size: 3.8vw; }
.detail-item.total { border-top: 1px solid #ddd; padding-top: 2vw; font-weight: 600; color: #ff6b35; }
.detail-item .amount { font-weight: 600; }
.deduction-note { font-size: 3.2vw; color: #666; text-align: center; margin-top: 2vw; padding: 2vw; background: #fff3cd; border-radius: 1vw; border: 1px solid #ffeaa7; }
</style>
